﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Portal.Nhibernate.Repository;

namespace Portal.Web.Areas.Admin.Controllers
{
    public class ProductController : BaseAdminController
    {
        private readonly IProductRepository<IProduct> _productRepository;

        public ProductController(IProductRepository<IProduct> productRepository)
        {
            _productRepository = productRepository;
        }
        public ProductController()
        {
            _productRepository = new ProductRepository();
        }

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetListJson(string categoryId = "", string sort = "Sort", string order = "DESC", int page = 1, int rows = 10, string name = "")
        {
            var list = _productRepository.GetSort(sort, order).Where(o => (o.CategoryId == categoryId || string.IsNullOrEmpty(categoryId)) && (o.NameEn.Contains(name) || o.Name.Contains(name) || string.IsNullOrEmpty(name))).Select(o => new Product { Id = o.Id, NameEn = o.NameEn, Name = o.Name, Model = o.Model, IsRecommend = o.IsRecommend, NormalImage = o.NormalImage, SmallImage = o.SmallImage, Sort = o.Sort, CategoryId = o.CategoryId }).JqEasyuiDataGrid(page, rows);
            return Json(list);
        }
        public ActionResult SearchControl()
        {

            return View();
        }


        public ActionResult Create()
        {
            if (Request.IsAjaxRequest())
                return View("CreateControl", _productRepository.CreateEntity());
            return View(_productRepository.CreateEntity());
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(FormCollection collection, Product entity, HttpPostedFileBase productImage, HttpPostedFileBase productSmallImage)
        {
            var model = _productRepository.CreateEntity();
            model.Culture = Culture;
            model.Founder = CurrentUserName;
            model.CategoryId = entity.CategoryId;
            model.DiscountPrice = entity.DiscountPrice;
            model.Description = entity.Description;
            model.IsClosed = entity.IsClosed;
            model.Price = entity.Price;
            model.Name = entity.Name;
            model.NameEn = entity.NameEn;
            model.DescriptionEn = entity.DescriptionEn;
            model.IsRecommend = entity.IsRecommend;
            model.Model = entity.Model;
            model.OverviewEn = entity.OverviewEn;
            model.Overview = entity.Overview;
            model.Parameters = entity.Parameters;
            model.ParametersEn = entity.ParametersEn;
            model.BigImage = entity.BigImage;
            model.NormalImage = entity.NormalImage;
            model.SmallImage = entity.SmallImage;
            model.Sort = entity.Sort;
            if (productImage != null)
            {
                var upload = new UploadHelper(productImage, "/Upload/Product/") { IsImage = true, PicMaxLength = 1024 * 1000 };
                if (!upload.Save())
                {
                    TempData["Result"] = upload.ErrorMessage;
                    if (Request.IsAjaxRequest())
                        return Json(new AjaxResult { state = true, message = upload.ErrorMessage });
                    return View(model);
                }

                model.NormalImage = upload.FileRelativePath;
            }
            if (productSmallImage != null)
            {
                var upload = new UploadHelper(productSmallImage, "/Upload/Product/") { IsImage = true, PicMaxLength = 1000 * 1024 };
                if (!upload.Save())
                {
                    TempData["Result"] = upload.ErrorMessage;
                    if (Request.IsAjaxRequest())
                        return Json(new AjaxResult { state = true, message = upload.ErrorMessage });
                    return View(model);
                }
                model.SmallImage = upload.FileRelativePath;
            }
            else
            {
                if (!string.IsNullOrEmpty(model.NormalImage.NullSafe()))
                {
                    model.SmallImage = model.NormalImage.Insert(
                             model.NormalImage.LastIndexOf("/", StringComparison.Ordinal) + 1, "jpeg-");
                    var xImage = new XImage();
                    xImage.ToThumbnail(model.NormalImage, model.NormalImage.Insert(model.NormalImage.LastIndexOf("/", System.StringComparison.Ordinal) + 1, "jpeg-"), 150, 150);
                }
            }
            _productRepository.Add(model);
            _productRepository.Save();
            ViewData["Result"] = new AjaxResult { message = "添加成功" };
            if (Request.IsAjaxRequest())
                return Json(new AjaxResult { state = true, message = "添加成功" });
            return View(_productRepository.CreateEntity());
        }



        public ActionResult Edit(string id)
        {

            var model = _productRepository.Get().SingleOrDefault(o => o.Id == id);
            if (Request.IsAjaxRequest())
                return View("EditControl", model);
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Product entity, FormCollection collection, HttpPostedFileBase productImage, HttpPostedFileBase productSmallImage)
        {
            var model = _productRepository.Get().SingleOrDefault(o => o.Id == entity.Id);
            if (model != null)
            {

                model.Culture = Culture;
                model.Founder = CurrentUserName;
                model.CategoryId = entity.CategoryId;
                model.DiscountPrice = entity.DiscountPrice;
                model.Description = entity.Description;
                model.IsClosed = entity.IsClosed;
                model.Price = entity.Price;
                model.Name = entity.Name;
                model.IsRecommend = entity.IsRecommend;
                model.NameEn = entity.NameEn;
                model.DescriptionEn = entity.DescriptionEn;
                model.Model = entity.Model;
                model.OverviewEn = entity.OverviewEn;
                model.Overview = entity.Overview;
                model.Parameters = entity.Parameters;
                model.ParametersEn = entity.ParametersEn;
                model.BigImage = entity.BigImage;
                model.NormalImage = entity.NormalImage;
                model.SmallImage = entity.SmallImage;
                model.Sort = entity.Sort;
                if (productImage != null)
                {
                    var upload = new UploadHelper(productImage, "/Upload/Product/") { IsImage = true, PicMaxLength = 1000 * 1024 };
                    if (!upload.Save())
                    {
                        TempData["Result"] = upload.ErrorMessage;
                        if (Request.IsAjaxRequest())
                            return Json(new AjaxResult { state = false, message = upload.ErrorMessage });
                        return View(model);
                    }
                    model.NormalImage = upload.FileRelativePath;
                }
                if (productSmallImage != null)
                {
                    var upload = new UploadHelper(productSmallImage, "/Upload/Product/") { IsImage = true, PicMaxLength = 1000 * 1024 };
                    if (!upload.Save())
                    {
                        TempData["Result"] = upload.ErrorMessage;
                        if (Request.IsAjaxRequest())
                            return Json(new AjaxResult { state = false, message = upload.ErrorMessage });
                        return View(model);
                    }
                    model.SmallImage = upload.FileRelativePath;
                }
                else
                {
                    if (productImage != null && !string.IsNullOrEmpty(model.NormalImage.NullSafe()))
                    {
                        model.SmallImage = model.NormalImage.Insert(
                              model.NormalImage.LastIndexOf("/", StringComparison.Ordinal) + 1, "jpeg-");
                        var xImage = new XImage();
                        xImage.ToThumbnail(model.NormalImage, model.NormalImage.Insert(model.NormalImage.LastIndexOf("/", System.StringComparison.Ordinal) + 1, "jpeg-"), 150, 150);
                    }
                }

                _productRepository.Update(model);
                _productRepository.Save();
                ViewData["Result"] = new AjaxResult { message = "修改成功" };
                if (Request.IsAjaxRequest())
                    return Json(new AjaxResult { state = true, message = "修改成功" });
                return View(model);

            }
            if (Request.IsAjaxRequest())
                return Json(new AjaxResult { state = false, message = "没有找到产品记录" });
            return NotFount(new AjaxResult { state = false, message = "没有找到产品记录" });
        }



        [HttpPost]
        public ActionResult Delete(IList<string> id, FormCollection collection)
        {

            var list = _productRepository.Get().Where(o => id.Contains(o.Id));
            list.ForEach(o => _productRepository.Delete(o));
            _productRepository.Save();
            return Json(new AjaxResult { state = true, message = "删除成功" });

        }
        /// <summary>
        /// Kndeditor文件上传
        /// </summary>
        /// <returns></returns>
        public void UploadFileProductJson()
        {
            var kndeditor = new KndeditorHelper(System.Web.HttpContext.Current, "Product", CurrentUserName);
            kndeditor.UploadJson();
        }
        /// <summary>
        /// Kndeditor文件管理
        /// </summary>
        public void FileManagerProductJson()
        {
            var kndeditor = new KndeditorHelper(System.Web.HttpContext.Current, "Product", CurrentUserName);
            kndeditor.FileManagerJson();
        }
    }
}
